package com.example.takeaway.service.impl;

import ch.qos.logback.classic.spi.EventArgUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.takeaway.common.BaseContext;
import com.example.takeaway.common.CustomException;
import com.example.takeaway.entity.*;
import com.example.takeaway.mapper.OrderMapper;
import com.example.takeaway.service.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@AllArgsConstructor
@Service

public class OrderServiceImpl extends ServiceImpl<OrderMapper , Orders> implements OrderService {


    private  final ShoppingCartService shoppingCartService;
    private final UserService userService;
    private final AddressBookService addressBookService;
    private final OrderDetailService orderDetailService;


    /**
     * 用户下单
     * @param orders
     */

    @Transactional
    @Override
    public void submit(Orders orders) {


        //获得当前用户id
        Long currentId = BaseContext.getCurrentId();

        //通过id 查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,currentId);

        List<ShoppingCart> list = shoppingCartService.list(wrapper);


        if(list == null || list.size() == 0){
            throw new CustomException("购物车为空, 不能下单");
        }

        //查询用户数据

        User userInfo = userService.getById(currentId);


        //查询地址数据

        AddressBook AddressInfo = addressBookService.getById(orders.getAddressBookId());

        if(AddressInfo == null){
            throw new CustomException("购物车地址为空");
        }


        long orderId = IdWorker.getId(); //订单号
        orders.setNumber(String.valueOf(orderId));


        //保证线程安全
        AtomicInteger amount = new AtomicInteger(0);

        // 计算总金额 + 订单明细
        List<OrderDetail>orderDetails = list.stream().map((item) -> {

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;

        }).collect(Collectors.toList());


        //向订单表插入数据 1 条


        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(currentId);
        orders.setUserName(userInfo.getName());
        orders.setConsignee(AddressInfo.getConsignee());
        orders.setPhone(AddressInfo.getPhone());

        orders.setAddress((AddressInfo.getProvinceName() == null ? "" : AddressInfo.getProvinceName())
                          +(AddressInfo.getCityName() == null ? "" : AddressInfo.getCityName())
                          +(AddressInfo.getDistrictName() == null ? "" : AddressInfo.getDistrictName())
                          +(AddressInfo.getDetail() == null ? "" : AddressInfo.getDetail())

        );



        this.save(orders);


        //向订单明细表插入数据  多条数据

        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(wrapper);


    }
}
